package com.qf.dao.impl;

import com.qf.dao.CouponDao;
import com.qf.entity.Coupon;
import com.qf.utils.DBUtils;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.apache.commons.dbutils.handlers.ScalarHandler;

import java.sql.SQLException;
import java.util.List;

public class CouponDaoImpl implements CouponDao {
    private QueryRunner qr = DBUtils.DB.getQr();

    @Override
    public int addCoupon(Coupon coupon) throws SQLException {
        String sql = "insert into coupon (cou_name,cou_content,cou_status,cou_remark) values(?,?,1,?)";
        Object[] objects = {coupon.getCou_name(), coupon.getCou_content(), coupon.getCou_remark()};
        int num = qr.update(sql, objects);
        return num;
    }

    @Override
    public int selectAllCouponCount() throws SQLException {
        String sql = "select count(1) from coupon";
        Long count = (Long) qr.query(sql, new ScalarHandler());
        return count == null ? 0 : Integer.parseInt(count + "");
    }

    @Override
    public List<Coupon> selectCouponListByPage(Integer currentPageNo, Integer pageSize) throws SQLException {
        String sql = "select * from coupon limit ?,?";
        Object[] objs = {(currentPageNo - 1) * pageSize, pageSize};
        return qr.query(sql, new BeanListHandler<>(Coupon.class), objs);
    }

    @Override
    public Coupon selectCouponByCid(Integer cid) throws SQLException {
        String sql = "select * from coupon where cou_id=?";
        Coupon coupon = qr.query(sql, new BeanHandler<>(Coupon.class), cid);
        return coupon;

    }

    @Override
    public int deleteCouponByCid(Integer cid) throws SQLException {
        String sql = "delete from coupon where cou_id=?";
        int delete = qr.update(sql, cid);
        return delete;

    }
}
